﻿namespace Codeplex.Unity.AutoRegister.Config
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    /// <summary>
    /// Provide RegistTypeTraits(Target type have UnityExportAttribute.)
    /// </summary>
    public class AssemblyRegistTypeTraitProvider : RegistTypeTraitProvider
    {
        private Assembly[] targetAssemblies;

        public AssemblyRegistTypeTraitProvider(params Assembly[] targetAssemblies)
        {
            this.targetAssemblies = targetAssemblies;
        }

        protected override IEnumerable<Type> GetTypes()
        {
            if (this.targetAssemblies == null)
            {
                return Enumerable.Empty<Type>();
            }

            return this.targetAssemblies
                .SelectMany(assembly => assembly.GetTypes())
                .Where(type => type.GetCustomAttributes(typeof(UnityExportAttribute), false).Any());
        }

        protected override IEnumerable<RegistTypeTrait> BuildTrait(Type type)
        {
            return AnnotationRegistTypeTraitBuilder.Build(type);
        }
    }
}
